package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.PcbSonFactoryInfoDao;
import com.sailfish.springbootdemo.dao.db2.PcbSpecialProcessDataDao;
import com.sailfish.springbootdemo.dao.db2.PcbSpecialProcessInfoDao;
import com.sailfish.springbootdemo.dao.db2.PcbSpecialProcessVersionDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.OperateLog;
import com.sailfish.springbootdemo.service.db2.PcbParentFactoryInfoService;
import com.sailfish.springbootdemo.service.db2.PcbSpecialProcessService;
import com.sailfish.springbootdemo.service.db4.OperateLogService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PcbSpecialProcessServiceImpl implements PcbSpecialProcessService {

    @Autowired
    PcbSpecialProcessInfoDao pcbSpecialProcessInfoDao;
    @Autowired
    PcbSpecialProcessDataDao pcbSpecialProcessDataDao;
    @Autowired
    PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    PcbParentFactoryInfoService pcbParentFactoryInfoService;
    @Autowired
    PcbSpecialProcessVersionDao pcbSpecialProcessVersionDao;
    @Autowired
    OperateService operateService;
    @Autowired
    OperateLogService operateLogService;

    @Override
    public List<PcbSpecialProcessInfo> getAllByLimit(String pcbSpecialProcessName, String pcbSpecialProcessNameEn, String version, Integer status) {
//        int begin = (page - 1) * pageSize;
//        System.out.println("begin===" + begin);
//        System.out.println("pageSize===" + pageSize);
        if (StringUtils.isBlank(version)) {
            version = getCurrentVersion();
        }
        List<PcbSpecialProcessInfo> allByLimit = pcbSpecialProcessInfoDao.getAllByLimit(pcbSpecialProcessName, pcbSpecialProcessNameEn, version, status);
        return allByLimit;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insert(PcbSpecialProcessInfo param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbSpecialProcessInfo search = new PcbSpecialProcessInfo();
            search.setPcbSpecialProcessName(param.getPcbSpecialProcessName());
            search.setPcbSpecialProcessNameEn(param.getPcbSpecialProcessNameEn());
            List<PcbSpecialProcessInfo> allByLimit = pcbSpecialProcessInfoDao.getAllByLimit2(param.getPcbSpecialProcessName(), param.getPcbSpecialProcessNameEn(), param.getVersion(), 1);
            if (allByLimit.stream().count() > 0) {
                return ResultUtil.error(500, "重复添加", "", null);
            } else {
                int count = pcbSpecialProcessInfoDao.insert(param);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺定义", 1, 1, new Date(), null, JSONObject.toJSONString(param)));
                    List<PcbSpecialProcessVersion> versionList = pcbSpecialProcessVersionDao.getByLimit(param.getVersion(), null);
                    if (versionList == null || versionList.size() == 0) {
                        PcbSpecialProcessVersion pcbSpecialProcessVersion = new PcbSpecialProcessVersion();
                        pcbSpecialProcessVersion.setVersion(param.getVersion());
                        pcbSpecialProcessVersion.setActive(1);
                        pcbSpecialProcessVersion.setSort(100);
                        pcbSpecialProcessVersion.setCreateTime(new Date());
                        pcbSpecialProcessVersion.setStatus(1);
                        count = pcbSpecialProcessVersionDao.insert(pcbSpecialProcessVersion);
                        if (count > 0) {
                            operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺版本", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessVersion)));
                        }
                    }
                    return ResultUtil.success(param);
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result delete(Integer id) {
        try {
            String userId = UserHeaderHolder.getUserId();
            String oldData = JSONObject.toJSONString(pcbSpecialProcessInfoDao.getById(id));
            int count = pcbSpecialProcessInfoDao.delete(id);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺定义", 2, 1, new Date(), oldData, null));
                List<PcbSpecialProcessData> dataDaoAllByLimit = pcbSpecialProcessDataDao.getAllByLimit(id, null, null, null);
                if (dataDaoAllByLimit.size() > 0) {
                    for (int i = 0; i < dataDaoAllByLimit.size(); i++) {
                        count = pcbSpecialProcessDataDao.delete(dataDaoAllByLimit.get(i).getPcbSpecialProcessDataId());
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺板厂", 2, 1, new Date(), JSONObject.toJSONString(dataDaoAllByLimit.get(i)), null));
                    }
                }
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result update(PcbSpecialProcessInfo param) {
        try {
            String userId = UserHeaderHolder.getUserId();
            String oldData = JSONObject.toJSONString(pcbSpecialProcessInfoDao.getById(param.getPcbSpecialProcessId()));
            int count = pcbSpecialProcessInfoDao.update(param);
            if (count > 0) {
                String newData = JSONObject.toJSONString(pcbSpecialProcessInfoDao.getById(param.getPcbSpecialProcessId()));
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺定义", 3, 1, new Date(), oldData, newData));
                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdatePcbSpecialProcessData(String data) {
        try {
            List<PcbSpecialProcessData> pcbSpecialProcessDataList = new ArrayList<>();
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pcbSpecialProcessInfoId = jsonObject.getInteger("pcbSpecialProcessId");
            String version = jsonObject.getString("version");
            if (pcbSpecialProcessInfoId == null) {
                return ResultUtil.error(500, "参数pcbSpecialProcessId为空", "param pcbSpecialProcessId is null", null);
            }
            String userId = UserHeaderHolder.getUserId();
            List<PcbSonFactoryInfo> allFactorys = pcbSonFactoryInfoDao.getAllByLimit(null);
            for (PcbSonFactoryInfo sonFac : allFactorys) {
                Integer sonFacId = sonFac.getPcbSonFactoryId();
                Integer isSatisfied = jsonObject.getInteger(sonFacId.toString());
                if (isSatisfied != null) {
                    PcbSpecialProcessData pcbSpecialProcessData = new PcbSpecialProcessData();
                    pcbSpecialProcessData.setPcbSpecialProcessInfoId(pcbSpecialProcessInfoId);
                    pcbSpecialProcessData.setFactoryId(sonFacId);
                    pcbSpecialProcessData.setSatisfied(isSatisfied);

                    pcbSpecialProcessData.setStatus(1);
                    pcbSpecialProcessData.setSort(100);
                    try {
                        List<PcbSpecialProcessData> allByLimit = pcbSpecialProcessDataDao.getAllByLimit(pcbSpecialProcessInfoId, sonFacId, version, null);
                        if (allByLimit != null && allByLimit.size() > 0) {
                            String oldData = JSONObject.toJSONString(allByLimit);
                            pcbSpecialProcessData.setUpdateTime(new Date());
                            int count = pcbSpecialProcessDataDao.updateByFacIdAndInfoId(pcbSpecialProcessData);
                            if (count > 0) {
                                String newData = JSONObject.toJSONString(pcbSpecialProcessDataDao.getAllByLimit(pcbSpecialProcessInfoId, sonFacId, version, null));
                                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺板厂", 3, 1, new Date(), oldData, newData));
                            }
                        } else {
                            pcbSpecialProcessData.setVersion(version);
                            pcbSpecialProcessData.setCreateTime(new Date());
                            int count = pcbSpecialProcessDataDao.insert(pcbSpecialProcessData);
                            if (count > 0) {
                                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺板厂", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessData)));
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
                    }
                    pcbSpecialProcessDataList.add(pcbSpecialProcessData);
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public List<PcbSpecialProcessInfo> getPcbSpecialProcessData(String pcbSpecialProcessName, String pcbSpecialProcessNameEn, String version, List<PcbSonFactoryInfo> factoryList) {
        try {

            final String userId = UserHeaderHolder.getUserId();
            OperateLog operateLog = new OperateLog(2,Integer.parseInt(userId) ,"特殊工艺开放能力",4,1,new Date(), UserHeaderHolder.getDomainAccount(), UserHeaderHolder.getIpAddress(), UserHeaderHolder.getNetworkSeg());
            boolean aa = operateLogService.addOperateLog(operateLog);

            if (StringUtils.isBlank(version)) {
                version = getCurrentVersion();
            }
            List<PcbSpecialProcessData> allSpecialProcessData = pcbSpecialProcessDataDao.getAllByLimit(null, null, version, null);
            Map<String, Integer> map = new HashMap<>();
            for (int i = 0; i < allSpecialProcessData.size(); i++) {
                String key = allSpecialProcessData.get(i).getFactoryId() + "-" + allSpecialProcessData.get(i).getPcbSpecialProcessInfoId();
                Integer value = allSpecialProcessData.get(i).getSatisfied();
                map.put(key, value);
            }
            if (factoryList == null) {
                factoryList = pcbSonFactoryInfoDao.getAllByLimit(null);
            }

            List<PcbSpecialProcessInfo> allByLimit = pcbSpecialProcessInfoDao.getAllByLimit(pcbSpecialProcessName, pcbSpecialProcessNameEn, version, 1);
            for (int i = 0; i < allByLimit.size(); i++) {
                Integer processInfoId = allByLimit.get(i).getPcbSpecialProcessId();
                List<SpecialProcessInfo> specialProcessInfos = new ArrayList<>();
                for (int j = 0; j < factoryList.size(); j++) {
                    Integer factoryId = factoryList.get(j).getPcbSonFactoryId();
                    SpecialProcessInfo specialProcessInfo = new SpecialProcessInfo();
                    specialProcessInfo.setFactoryId(factoryId);
                    if (map.containsKey(factoryId + "-" + processInfoId)) {
                        specialProcessInfo.setSatisfied(map.get(factoryId + "-" + processInfoId));
                    } else {
                        specialProcessInfo.setSatisfied(null);
                    }
                    specialProcessInfos.add(specialProcessInfo);
                }
                allByLimit.get(i).setData(specialProcessInfos);
            }
            return allByLimit;
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public List<SpecialProcessVM> getPcbSpecialProcessDataByFactory(String version, PcbSonFactoryInfo pcbSonFactoryInfo) {
        try {
            if (StringUtils.isBlank(version)) {
                version = getCurrentVersion();
            }
            List<SpecialProcessVM> list = new ArrayList<>();

            List<PcbSpecialProcessData> allSpecialProcessData = pcbSpecialProcessDataDao.getAllByLimit(null, pcbSonFactoryInfo.getPcbSonFactoryId(), version, 1);
            List<PcbSpecialProcessInfo> allByLimit = pcbSpecialProcessInfoDao.getAllByLimit(null, null, version, 1);
            Map<Integer, PcbSpecialProcessInfo> map = new HashMap<>();

            for (int i = 0; i < allByLimit.size(); i++) {
                map.put(allByLimit.get(i).getPcbSpecialProcessId(), allByLimit.get(i));
            }
            for (int i = 0; i < allSpecialProcessData.size(); i++) {
                SpecialProcessVM specialProcessVM = new SpecialProcessVM();
                PcbSpecialProcessInfo pcbSpecialProcessInfo = map.get(allSpecialProcessData.get(i).getPcbSpecialProcessInfoId());
                specialProcessVM.setPcbSpecialProcessName(pcbSpecialProcessInfo.getPcbSpecialProcessName());
                specialProcessVM.setPcbSpecialProcessNameEn(pcbSpecialProcessInfo.getPcbSpecialProcessNameEn());
                list.add(specialProcessVM);
            }
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public PcbSpecialProcessInfo getById(Integer id) {
        return pcbSpecialProcessInfoDao.getById(id);
    }

    @Override
    public String getCurrentVersion() {
        List<PcbSpecialProcessVersion> byVersionOrder = pcbSpecialProcessVersionDao.getByVersionOrder();
        if (byVersionOrder != null && byVersionOrder.size() > 0) {
            return byVersionOrder.get(0).getVersion();
        } else {
            return "1.0";
        }
    }

    @Override
    public Result upgrade(String newVersion) {
        String userId = UserHeaderHolder.getUserId();
        String oldVersion = getCurrentVersion();
        List<PcbSpecialProcessInfo> pcbSpecialProcessInfos = pcbSpecialProcessInfoDao.getAllByLimit(null, null, oldVersion, null);
        for (int i = 0; i < pcbSpecialProcessInfos.size(); i++) {
            PcbSpecialProcessInfo newVer_processInfo = new PcbSpecialProcessInfo();
            newVer_processInfo.setVersion(newVersion);
            newVer_processInfo.setPcbSpecialProcessName(pcbSpecialProcessInfos.get(i).getPcbSpecialProcessName());
            newVer_processInfo.setPcbSpecialProcessNameEn(pcbSpecialProcessInfos.get(i).getPcbSpecialProcessNameEn());
            newVer_processInfo.setRemark(pcbSpecialProcessInfos.get(i).getRemark());
            newVer_processInfo.setCreateTime(new Date());
            newVer_processInfo.setStatus(1);
            newVer_processInfo.setSort(100);
            newVer_processInfo.setCreateUser(userId);
            Integer count = pcbSpecialProcessInfoDao.insert(newVer_processInfo);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺定义", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessInfos)));
            }
            List<PcbSpecialProcessData> dataList = pcbSpecialProcessDataDao.getAllByLimit(pcbSpecialProcessInfos.get(i).getPcbSpecialProcessId(), null, null, null);
            if (dataList.size() > 0) {
                for (int j = 0; j < dataList.size(); j++) {
                    PcbSpecialProcessData pcbSpecialProcessData = new PcbSpecialProcessData();
                    pcbSpecialProcessData.setPcbSpecialProcessInfoId(newVer_processInfo.getPcbSpecialProcessId());
                    pcbSpecialProcessData.setFactoryId(dataList.get(j).getFactoryId());
                    pcbSpecialProcessData.setSatisfied(dataList.get(j).getSatisfied());
                    pcbSpecialProcessData.setRemark(dataList.get(j).getRemark());
                    pcbSpecialProcessData.setCreateTime(new Date());
                    pcbSpecialProcessData.setCreateUser(userId);
                    pcbSpecialProcessData.setVersion(newVersion);
                    count = pcbSpecialProcessDataDao.insert(pcbSpecialProcessData);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺板厂", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessData)));
                    }
                }
            }

        }

        List<PcbSpecialProcessVersion> versionList = pcbSpecialProcessVersionDao.getByLimit(newVersion, null);
        if (versionList == null || versionList.size() == 0) {
            PcbSpecialProcessVersion pcbSpecialProcessVersion = new PcbSpecialProcessVersion();
            pcbSpecialProcessVersion.setVersion(newVersion);
            pcbSpecialProcessVersion.setActive(1);
            pcbSpecialProcessVersion.setSort(100);
            pcbSpecialProcessVersion.setCreateTime(new Date());
            pcbSpecialProcessVersion.setStatus(1);
            Integer count = pcbSpecialProcessVersionDao.insert(pcbSpecialProcessVersion);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺版本", 1, 1, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessVersion)));
            }
        }
        return ResultUtil.success(null);
    }

    @Override
    public List<PcbSpecialProcessVersion> getVersionList() {
        return pcbSpecialProcessVersionDao.getByLimit(null, null);
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result readExcel(HttpServletRequest req) {
        List<PcbSpecialProcessInfo> pcbSpecialProcessInfos = new ArrayList<>();
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
        MultipartFile file = mRequest.getFile("file");
        XSSFWorkbook workbook = null;
        XSSFRow row = null;
        XSSFSheet sheet = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, "read excel error:" + e.getMessage(), "read excel error:" + e.getMessage(), null);
        }
        sheet = workbook.getSheetAt(0);
        if (sheet != null) {
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                row = sheet.getRow(i);
                PcbSpecialProcessInfo pcbSpecialProcessInfo = new PcbSpecialProcessInfo();
                String rowCellData0 = row.getCell(0).toString();
                String rowCellData1 = row.getCell(1).toString();
                String rowCellData2 = row.getCell(2).toString();
                pcbSpecialProcessInfo.setPcbSpecialProcessName(rowCellData0);
                pcbSpecialProcessInfo.setPcbSpecialProcessNameEn(rowCellData1);
                pcbSpecialProcessInfo.setVersion(rowCellData2);
                pcbSpecialProcessInfos.add(pcbSpecialProcessInfo);
            }
        }
        try {
            String userId = UserHeaderHolder.getUserId();
            if (pcbSpecialProcessInfos.size() > 0) {
                int count = pcbSpecialProcessInfoDao.insertBatch(pcbSpecialProcessInfos);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB特殊工艺定义", 1, 2, new Date(), null, JSONObject.toJSONString(pcbSpecialProcessInfos)));
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Value("${personal.config.file.file-save-url}")
    private String rootPath;

    @Override
    public Result outputSpecialProcessParam(String pcbSpecialProcessName, String pcbSpecialProcessNameEn, String version) {
        try {

            final String userId = UserHeaderHolder.getUserId();
            OperateLog operateLog = new OperateLog(2,Integer.parseInt(userId) ,"特殊工艺开放能力",5,1,new Date(), UserHeaderHolder.getDomainAccount(), UserHeaderHolder.getIpAddress(), UserHeaderHolder.getNetworkSeg());
            boolean aa = operateLogService.addOperateLog(operateLog);

            List<PcbSpecialProcessInfo> allParams = pcbSpecialProcessInfoDao.getAllByLimit(pcbSpecialProcessName, pcbSpecialProcessNameEn, version, 1);
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");
            XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
            setBorder.setBorderBottom(BorderStyle.THIN);
            setBorder.setBorderLeft(BorderStyle.THIN);
            setBorder.setBorderRight(BorderStyle.THIN);
            setBorder.setBorderTop(BorderStyle.THIN);

            //创建字体 加粗
            XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);
            font.setFontHeight(11);
            style.setFont(font);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder.setFont(font);

            XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
            setBorder2.setBorderBottom(BorderStyle.THIN);
            setBorder2.setBorderLeft(BorderStyle.THIN);
            setBorder2.setBorderRight(BorderStyle.THIN);
            setBorder2.setBorderTop(BorderStyle.THIN);

            Row row_t1 = sheet.createRow(0);
            Cell row_t1Cell = row_t1.createCell(0);
            row_t1Cell.setCellValue("特殊工艺英文名称");
            row_t1Cell.setCellStyle(setBorder);
            Cell row_t1Cell2 = row_t1.createCell(1);
            row_t1Cell2.setCellValue("特殊工艺中文名称");
            row_t1Cell2.setCellStyle(setBorder);
            Cell row_t1Cell3 = row_t1.createCell(2);
            row_t1Cell3.setCellValue("版本");
            row_t1Cell3.setCellStyle(setBorder);
            sheet.setColumnWidth(0, 50 * 256);
            sheet.setColumnWidth(1, 50 * 256);
            sheet.setColumnWidth(2, 50 * 256);
            for (int i = 0; i < allParams.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Cell rowCell = row.createCell(0);
                rowCell.setCellValue(allParams.get(i).getPcbSpecialProcessNameEn());
                rowCell.setCellStyle(setBorder2);
                Cell rowCell1 = row.createCell(1);
                rowCell1.setCellValue(allParams.get(i).getPcbSpecialProcessName());
                rowCell1.setCellStyle(setBorder2);
                Cell rowCell2 = row.createCell(2);
                rowCell2.setCellValue(allParams.get(i).getVersion());
                rowCell2.setCellStyle(setBorder2);
            }
            // 导出Excel文件
            String filename = "pcb特殊工艺参数" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result outputSpecialProcessData(String pcbSpecialProcessName, String pcbSpecialProcessNameEn, String version) {
        try {
            final String userId = UserHeaderHolder.getUserId();
            OperateLog operateLog = new OperateLog(2,Integer.parseInt(userId) ,"特殊工艺开放能力",5,1,new Date(), UserHeaderHolder.getDomainAccount(), UserHeaderHolder.getIpAddress(), UserHeaderHolder.getNetworkSeg());
            boolean aa = operateLogService.addOperateLog(operateLog);

            List<PcbSpecialProcessInfo> allParams = getPcbSpecialProcessData(pcbSpecialProcessName, pcbSpecialProcessNameEn, version, null);

            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");
            XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
            setBorder.setBorderBottom(BorderStyle.THIN);
            setBorder.setBorderLeft(BorderStyle.THIN);
            setBorder.setBorderRight(BorderStyle.THIN);
            setBorder.setBorderTop(BorderStyle.THIN);

            //创建字体 加粗
            XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);
            font.setFontHeight(11);
            style.setFont(font);
            style.setVerticalAlignment(VerticalAlignment.CENTER);

            setBorder.setFont(font);
            XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
            setBorder2.setBorderBottom(BorderStyle.THIN);
            setBorder2.setBorderLeft(BorderStyle.THIN);
            setBorder2.setBorderRight(BorderStyle.THIN);
            setBorder2.setBorderTop(BorderStyle.THIN);

            Row row_t1 = sheet.createRow(1);
            Cell row_t1Cell0 = row_t1.createCell(0);
            row_t1Cell0.setCellValue("序号");
            row_t1Cell0.setCellStyle(setBorder);
            Cell row_t1Cell1 = row_t1.createCell(1);
            row_t1Cell1.setCellValue("特殊工艺英文名称");
            row_t1Cell1.setCellStyle(setBorder);
            Cell row_t1Cell2 = row_t1.createCell(2);
            row_t1Cell2.setCellValue("特殊工艺中文名称");
            row_t1Cell2.setCellStyle(setBorder);
            Cell row_t1Cell3 = row_t1.createCell(3);
            row_t1Cell3.setCellValue("版本");
            row_t1Cell3.setCellStyle(setBorder);

            sheet.setColumnWidth(0, 10 * 256);
            sheet.setColumnWidth(1, 40 * 256);
            sheet.setColumnWidth(2, 40 * 256);
            sheet.setColumnWidth(3, 10 * 256);
            Row rowT2 = sheet.createRow(2);
            int columIndex=4;
            List<Integer> pcbFactoryIds_new = new ArrayList<>();
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoService.getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);
            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++)
            {
                Cell celli = row_t1.createCell(columIndex);
                celli.setCellStyle(setBorder);
                celli.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyName());
                int startIndexT = columIndex;
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null && sonFactoryInfos.size() > 0) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        Cell cell2j = rowT2.createCell(columIndex);
                        cell2j.setCellValue(sonFactoryInfos.get(j).getSonFactoryName());
                        cell2j.setCellStyle(setBorder);
                        columIndex++;
                        pcbFactoryIds_new.add(sonFactoryInfos.get(j).getPcbSonFactoryId());
                    }
                    CellRangeAddress region3 = new CellRangeAddress(1, 1, startIndexT, columIndex - 1);
                    if (columIndex - 1 > startIndexT) {
                        sheet.addMergedRegion(region3);
                    }
                }
                else {
                    columIndex++;
                    pcbFactoryIds_new.add(-1);
                }
            }

            int rowIndex = 3;
            int seq = 1;
            for (int i = 0; i < allParams.size(); i++) {
                Row row = sheet.createRow(rowIndex);
                rowIndex++;
                Cell rowCell0 = row.createCell(0);
                rowCell0.setCellValue(seq);
                rowCell0.setCellStyle(setBorder2);
                Cell rowCell1 = row.createCell(1);
                rowCell1.setCellValue(allParams.get(i).getPcbSpecialProcessNameEn());
                rowCell1.setCellStyle(setBorder2);
                Cell rowCell2 = row.createCell(2);
                rowCell2.setCellValue(allParams.get(i).getPcbSpecialProcessName());
                rowCell2.setCellStyle(setBorder2);
                Cell rowCell3 = row.createCell(3);
                rowCell3.setCellValue(allParams.get(i).getVersion());
                rowCell3.setCellStyle(setBorder2);

                List<SpecialProcessInfo> data = allParams.get(i).getData();
                for (int j = 0; j < pcbFactoryIds_new.size(); j++) {
                    Integer fid = pcbFactoryIds_new.get(j);
                    Cell row_tjCell = row.createCell(j + 4);
                    final List<SpecialProcessInfo> collect = data.stream().filter(x -> x.getFactoryId().equals(fid)).collect(Collectors.toList());
                    if(collect.size()>0){
                        Integer satisfied = data.get(j).getSatisfied();
                        String s = satisfied == null ? "" : satisfied == 1 ? "满足" : "不满足";
                        row_tjCell.setCellValue(s);
                        row_tjCell.setCellStyle(setBorder2);
                    }
                    else{
                        row_tjCell.setCellValue("");
                        row_tjCell.setCellStyle(setBorder2);
                    }
                }
            }
            //加边框
            int columnCount = 4 + pcbFactoryIds_new.size();
            for (int i = 1; i <= 2; i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell celli = row.getCell(j);
                    if (celli == null) {
                        celli = row.createCell(j);
                        celli.setCellStyle(setBorder);
                    } else {
                        if (celli.getCellStyle() == null) {
                            celli.setCellStyle(setBorder);
                        } else {
                            if (celli.getCellStyle().getFillForegroundColor() != IndexedColors.GREEN.getIndex()
                                    && celli.getCellStyle().getFillForegroundColor() != IndexedColors.RED.getIndex()) {
                                celli.setCellStyle(setBorder);
                            }
                        }
                    }
                }
            }
            //合并单元格
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(1, 2, 3, 3));
            // 导出Excel文件
            String filename = "pcb特殊工艺数据" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public List<CapacityMatch> getCapacityMatch(List<PcbSonFactoryInfo> sonFactoryInfoList, List<PcbSpecialProcessInfo> pcbSpecialProcessInfos) {
        List<CapacityMatch> list = new ArrayList<>();
        String version = getCurrentVersion();
        String requireSpecialProcess = "";
        if (pcbSpecialProcessInfos != null) {
            for (int j = 0; j < pcbSpecialProcessInfos.size(); j++) {
                requireSpecialProcess += pcbSpecialProcessInfos.get(j).getPcbSpecialProcessName() + ",";
            }
        }
        if (pcbSpecialProcessInfos.size() == 0) {
            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                CapacityMatch capacityMatch = new CapacityMatch();
                capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                capacityMatch.setParamKey("specialProcess");
                capacityMatch.setParamName("特殊工艺");
                capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));
                capacityMatch.setIsSatisfied("是");
                list.add(capacityMatch);
            }
        } else {

            for (int i = 0; i < sonFactoryInfoList.size(); i++) {
                boolean flag = true;
                Integer factoryId = sonFactoryInfoList.get(i).getPcbSonFactoryId();
                for (int j = 0; j < pcbSpecialProcessInfos.size(); j++) {
                    Integer pcbSpecialProcessId = pcbSpecialProcessInfos.get(j).getPcbSpecialProcessId();
                    List<PcbSpecialProcessData> pcbSpecialProcessDataList = pcbSpecialProcessDataDao.getAllByLimit(pcbSpecialProcessId, factoryId, version, 1);
                    if (pcbSpecialProcessDataList == null || pcbSpecialProcessDataList.size() == 0) {
                        flag = false;
                        break;
                    }
                }
                CapacityMatch capacityMatch = new CapacityMatch();
                capacityMatch.setPcbSonFactoryInfoId(sonFactoryInfoList.get(i).getPcbSonFactoryId());
                capacityMatch.setParamKey("specialProcess");
                capacityMatch.setParamName("特殊工艺");
                capacityMatch.setPcbSonFactoryInfo(sonFactoryInfoList.get(i));

                if (flag) {
                    capacityMatch.setIsSatisfied("是");
                } else {
                    capacityMatch.setIsSatisfied("否");
                    String reason = "单板特殊工艺要求为:" + requireSpecialProcess + " 板厂无单板要求的特殊工艺;";
                    capacityMatch.setReason(reason);
                }
                list.add(capacityMatch);
            }
        }

        return list;
    }


    public List<Integer> getCapacityMatchData(Integer pcbSpecialProcessId, String version) {
        List<PcbSpecialProcessData> pcbSpecialProcessDataList = pcbSpecialProcessDataDao.getAllByLimit(pcbSpecialProcessId, null, version, null);
        List<Integer> satisfiedFactory = new ArrayList<>();

        if (pcbSpecialProcessDataList != null && pcbSpecialProcessDataList.size() > 0) {
            for (int i = 0; i < pcbSpecialProcessDataList.size(); i++) {
                if (pcbSpecialProcessDataList.get(i).getSatisfied() == 1) {
                    satisfiedFactory.add(pcbSpecialProcessDataList.get(i).getFactoryId());
                }
            }
        }
        return satisfiedFactory;
    }
}
